package com.edu.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.edu.demo.entity.Contract;
import com.edu.demo.entity.Sign;
import com.edu.demo.exception.MyNullPointerException;
import com.edu.demo.exception.UpdateErrorException;
import com.edu.demo.mapper.SignMapper;
import com.edu.demo.service.IContractService;
import com.edu.demo.service.ISignService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 签到表 服务实现类
 * </p>
 *
 * @author jixuewei
 * @since 2023-01-12
 */
@Service
public class SignServiceImpl extends ServiceImpl<SignMapper, Sign> implements ISignService {

    @Autowired
    private SignMapper signMapper;

    @Autowired
    private IContractService contractService;

    /**
     * 查询某一天是否存在签到记录
     *
     * @param stuId
     * @param date
     * @return
     */
    @Override
    public Sign selectByDateAndStuId(Integer stuId, Date date) {
        QueryWrapper<Sign> queryWrapper = new QueryWrapper<>();
        date.setHours(0);
        date.setMinutes(0);
        Date date1 = new Date();
        date1.setHours(23);
        date1.setMinutes(59);
        queryWrapper.eq("stu_id",stuId);
        queryWrapper.ge("date_time",date);
        queryWrapper.le("date_time",date1);
        Sign sign = signMapper.selectOne(queryWrapper);
        return sign;
    }

    /**
     * 签到
     *
     * @param sign
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateSign(Sign sign) throws UpdateErrorException {
        QueryWrapper<Sign> queryWrapper = new QueryWrapper<>();

        Date date = new Date(), date1 = new Date();
        date.setHours(0);
        date.setMinutes(0);
        date1.setHours(23);
        date1.setMinutes(59);
        queryWrapper.eq("stu_id",sign.getStuId());
        queryWrapper.ge("date_time",date);
        queryWrapper.le("date_time",date1);
        int update = signMapper.update(sign, queryWrapper);
        if(update==1) return true;
        throw new UpdateErrorException("更新有误");
    }

    /**
     * 查询某个项目date的签到
     *
     * @param date
     * @param projectId
     * @return
     */
    @Override
    public List<Sign> thisMonth(Date date, Integer projectId) throws MyNullPointerException{
        List<Contract> contracts = contractService.list(new QueryWrapper<Contract>().eq("project_id", projectId));
        if(contracts.isEmpty()) throw new MyNullPointerException("该项目没有学生签订合同");
        List<Integer> stuIds = contracts.stream().map(Contract::getStuId).collect(Collectors.toList());

        List<Sign> signs = signMapper.selectThisMonth(date, stuIds);
        return signs;

    }
}
